const WebSocket = require('ws');
const http = require('http');
const XMLHttpRequest = require('xhr2');
 
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('WebSocket Server\n');
});
 
const wss = new WebSocket.Server({ server, origin: '*' });


let currentFileIndex = 0
const fileList = [
  {name: '1-WakeVelocity-DVP-40rpm-back0.5m-r0.5m.xlsx'},
  {name: '2-WakeVelocity-DVP-40rpm-back1m-r0.5m.xlsx'},
  {name: '3-WakeVelocity-DVP-40rpm-back1.5m-r0.5m.xlsx'},
  {name: '4-WakeVelocity-DVP-40rpm-back2m-r0.5m.xlsx'},
  {name: '5-WakeVelocity-DVP-40rpm-back2.5m-r0.5m.xlsx'},
]
wss.on('connection', (ws) => {
  console.log('connect OK!');
 
  ws.on('message', (message) => {
    console.log('收到消息：', message);
 
    // 向客户端发送消息
    setInterval(() => {
      if (currentFileIndex < fileList.length) {
        const fileName = fileList[currentFileIndex].name
        console.log(currentFileIndex);
        
        // getFileFromUrl('http://localhost:3005/docs/excel/'+fileName, fileName).then((file) => {
        //   sendFile(ws, file)
        //   currentFileIndex = currentFileIndex + 1
        // });
        ws.send(`http://localhost:3000/${fileName}`);
        currentFileIndex = currentFileIndex + 1
      }
      //  ws.send('/api/Interface/userInfo');
    }, 1000);
 
  });
 
  // 连接关闭时的回调
  ws.on('close', () => {
    console.log('客户端已断开连接');
  });
});
 
server.listen(3005, () => {
  console.log('WebSocket 服务器已启动在 http://localhost:3005');
});

// 发送文件
function sendFile(webSocketInstance, file) {
  var reader = new FileReader();
  reader.onload = function(event) {
    var arrayBuffer = event.target.result;
    webSocketInstance.send(arrayBuffer);
    webSocketInstance.send(111);
  };
  reader.readAsArrayBuffer(file);
}

/**
 * 文件链接获取文件
 * @param {*} url 文件链接地址
 * @param {*} fileName 文件名
 * @returns 
 */
function getFileFromUrl(url, fileName) {
  return new Promise((resolve, reject) => {
    var blob = null;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.setRequestHeader('Accept', 'image/png');
    xhr.responseType = "blob";
    // 加载时处理
    xhr.onload = () => {
      // 获取返回结果
      blob = xhr.response;
      let file= new File([blob], fileName, { type: 'image/png' });
      // 返回结果
      resolve(file);
    };
    xhr.onerror = (e) => {
      reject(e)
    };
    // 发送
    xhr.send();
  });
}